package com.xfcy.blog.service.impl;

import com.xfcy.blog.common.R;
import com.xfcy.blog.common.constant.RedisConstant;
import com.xfcy.blog.common.constant.SqlConstant;
import com.xfcy.blog.common.enums.UploadEnum;
import com.xfcy.blog.service.CloudOssService;
import com.xfcy.blog.service.SystemConfigService;
import com.xfcy.blog.strategy.context.FileUploadStrategyContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author 晓风残月Lx
 * @date 2023/5/4 11:48
 */
@Service
public class CloudOssServiceImpl implements CloudOssService {

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private FileUploadStrategyContext fileUploadStrategyContext;

    @Resource
    private RedisTemplate redisTemplate;

    String strategy;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public R upload(MultipartFile file) {
        if (file.getSize() > 1024 * 1024 * 10) {
            return R.error("文件大小不能大于10M");
        }

        // 获取文件后缀
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return R.error("请选择jpg,jpeg,gif,png格式的图片");
        }
        getFileUploadStrategy();
        String key = fileUploadStrategyContext.executeFileUploadStrategy(strategy, file, suffix);

        // 将上传的图片存入redis
        redisTemplate.opsForSet().add(RedisConstant.FILE_UPLOAD_IMAGES, key);

        return R.success(key);
    }

    @Override
    public R delBatchFile(String... key) {
        getFileUploadStrategy();
        Boolean aBoolean = fileUploadStrategyContext.executeFileDeleteStrategy(strategy, key);
        if (!aBoolean) {
            return R.error("删除文件失败！");
        }
        return R.success("删除成功！");
    }

    @Override
    public List<String> getAllImages() {
        return fileUploadStrategyContext.executeFileInfoStrategy(strategy);
    }


    private void getFileUploadStrategy() {
        strategy = UploadEnum.getStrategy(systemConfigService.getCustomizeOne().getFileUploadWay());
    }
}
